<script setup>
import { computed, onMounted, ref } from 'vue';
import { useBlogsStore } from '@/stores/blog.js';
import BlogComment from '@/components/BlogComment.vue'
import BlogDivider from '@/components/BlogDivider.vue'
import { MdPreview } from 'md-editor-v3';
import { useEditorStore } from '@/stores/editor';
import { useGlobalStore } from '@/stores/global';

const props = defineProps({
    id: {
        type: Object,
        require: true
    }
})

const globalStore = useGlobalStore()

const editorStore = useEditorStore()

const blogsStore = useBlogsStore()
const blog = ref({});

// const text = ref('');
let text = ref("# SpringBoot 文件上传\n\n通过`MultipartFile`实现文件上传。\n\n## 1. 相关配置配置\n\n### 1.1 设置静态资源目录\n#### 方式1：通过 application.yml 文件配置\n```yml\nspring:\n  mvc:\n    static-path-pattern: /uploads/** # 静态资源路径匹配模式,即URL路径以/uploads开头，例如：http://localhost:8089/uploads/img/111.png，默认是 /**\n  web:\n    resources:\n      static-locations:\n        - classpath:/META-INF/resources/\n        - classpath:/resources/\n        - classpath:/static/\n        - classpath:/public/\n        - file:/var/resign/uploads/ # 设置静态资源所在的实际路径\n```\n#### 方式2：通过WebMvcConfigurer配置文件配置\n此种方式更灵活一些\n```java\npackage com.fengye.resign.config;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\n\n/**\n * @author fengye\n * @version 1.0\n * @date 2024/5/28 13:53:25\n * @description WebMvcConfigurer\n */\n@Configuration\npublic class WebMvcConfig implements WebMvcConfigurer {\n\n    @Value(\"${files.upload.path}\")\n    private  String fileUploadPath;\n    @Override\n    public void addResourceHandlers(ResourceHandlerRegistry registry) {\n        registry.addResourceHandler(\"/uploads/**\") // 访问路径前缀，如：http://localhost:8089/uploads/img/111.png 中的/uploads\n                .addResourceLocations(\"file:\" + fileUploadPath); // 文件存储位置\n    }\n}\n```\n\n### 1.2 设置上传文件大小限制\n```yml\nspring:\n  # servlet配置\n  servlet:\n    multipart:\n      # 有两种方法设置文件最大值以及请求最大值，一种是在properties文件中配置下面这俩字段，另一种方法是在主类（QubanApplication）中用代码设置，详情参见主类中相关代码\n      max-file-size: 1024MB\n      max-request-size: 1024MB\n```\n\n## 2. 文件上传代码\n```java\npackage com.fengye.resign.controller;\n\nimport cn.hutool.core.io.FileUtil;\nimport cn.hutool.core.util.StrUtil;\nimport cn.hutool.crypto.SecureUtil;\nimport com.fengye.common.domain.entity.Files;\nimport com.fengye.common.domain.ResponseResult;\nimport com.fengye.service.service.FileService;\nimport io.swagger.annotations.Api;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.multipart.MultipartFile;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.UUID;\n\n/**\n * @author sunlei\n * @version 1.0\n * @date 2024/5/27 14:53:56\n * @description 文件上传\n */\n@Api(tags = \"文件上传模块\")\n@Slf4j\n@RestController\n@RequestMapping(\"/resign\")\npublic class FileController {\n\n    //文件磁盘路径\n    @Value(\"${files.upload.path}\")\n    private  String fileUploadPath;\n\n    @Autowired\n    private FileService fileService;\n\n    @PostMapping(value = \"/upload\")\n    public ResponseResult<Void> uploadFile(@RequestPart MultipartFile file) throws IOException {\n        // 获取文件原始名称\n        String originalFilename = file.getOriginalFilename();\n        // 获取文件名后缀\n        String suffix = FileUtil.extName(originalFilename);\n        // 获取文件大小，转成KB\n        long size = file.getSize()/1024;\n\n        // 文件存储的目录\n        File uploadParentFile = new File(fileUploadPath);\n        // 判断文件目录是否存在\n        if (!uploadParentFile.exists()) {\n            // 如果不存在就创建文件夹\n            uploadParentFile.mkdirs();\n        }\n\n        // 定义一个文件以为标识码（UUID）\n        String fileName = generateFileName(suffix);\n        String localFilePath = fileUploadPath + fileName;\n        File localFile = new File(localFilePath);\n\n        String url;\n        // 获取文件的md5\n        String md5 = SecureUtil.md5(file.getInputStream());\n        // 从数据库查询是否存在相同的记录\n        Files dbFiles = fileService.getFileByMd5(md5);\n        if (dbFiles != null) { // 文件已存在\n            url = dbFiles.getUrl();\n        } else {\n            // 上传文件到磁盘\n            file.transferTo(localFile);\n            // 数据库若不存在重复文件，则不删除刚才上传的文件\n            url = fileName;\n        }\n\n        //存储至数据库\n        Files saveFile = new Files();\n        saveFile.setName(originalFilename);\n        saveFile.setType(suffix);\n        saveFile.setSize(size);\n        saveFile.setUrl(url); // 访问的时候需要拼接 http://localhost:8089/uploads/\n        saveFile.setMd5(md5);\n        fileService.save(saveFile);\n\n        return ResponseResult.success(\"上传成功\");\n    }\n\n    String generateFileName(String suffix) {\n        String fileName = UUID.randomUUID().toString() + StrUtil.DOT + suffix;\n        return fileName;\n    }\n}\n```");

const currentTheme = computed(() => { 
    return globalStore ? 'dark' : 'light';
 });

onMounted(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    blogsStore.getBlogById(props.id).then((result)=>{
        blog.value = result;
        // text.value = result.content;
    })
})

const onGetCatalog = (catalog) => {
    if (!catalog) return;
    console.log('文章目录~~~~~~：', catalog)
    editorStore.updateCatelog(catalog);
}
</script>

<template>
    <div class="blog-container" v-if="blog">
        <MdPreview class="blog-content" :theme="currentTheme" :editorId="editorStore.editorId" :modelValue="text" @onGetCatalog="onGetCatalog" />
        <div class="copyright">
            <div><span>文章作者：</span><a href="http://localhost:5173/about">FY</a></div>
            <div><span>文章链接：</span><a href="http://localhost:5173/detail/110000197606252657">http://localhost:5173/detail/110000197606252657</a></div>
            <div><span>版权声明：</span>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0 </a>许可协议。转载请注明来自 <a>FY's Blog！</a></div>
        </div>
        <BlogDivider class="blog-divider" />
        <BlogComment class="blog-comment" :blog="blog"/>
    </div>
</template>

<style lang="scss" scoped>

.blog-container {
    display: flex;
    flex-direction: column;
    align-items: cennter;
    text-align: left;
    padding: 0 10px 20px 10px;
    @include border;
    @include box-shadow;
    // background-color: orange;

    .copyright {
        // color: $text-color-333;
        font-size: 13px;
        line-height: 25px;
        padding: 15px;
        border: 1px solid var(--divider-color);
        // background-color: paleturquoise;
        span {
            font-size: 14px;
            color: var(--primary-color);
            font-weight: bolder;
        }
        a {
            color: $text-color-777;
        }
    }

    .copyright, .blog-divider, .blog-comment {
        margin: 15px;
    }
}

</style>
